package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.api.RemoteExtPageService;
import com.ruoyi.business.domain.ExtButton;
import com.ruoyi.business.domain.ExtPage;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.domain.ImpMenu;
import com.ruoyi.system.domain.NoPermissionButton;
import com.ruoyi.system.domain.SysMenu;
import com.ruoyi.system.domain.pageparse.TempNode;
import com.ruoyi.system.domain.vo.MetaVo;
import com.ruoyi.system.domain.vo.RouterVo;
import com.ruoyi.system.domain.vo.TreeSelect;
import com.ruoyi.system.mapper.SysMenuMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysRoleMenuMapper;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.utils.PageParseTreeBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 菜单 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysMenuServiceImpl implements ISysMenuService
{
    public static final String PREMISSION_STRING = "perms[\"{0}\"]";

    @Autowired
    private SysMenuMapper menuMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private RemoteExtPageService pageService;
    /**
     * 根据用户查询系统菜单列表
     *
     * @param userId 用户ID
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuList(Long userId)
    {
        return selectMenuList(new SysMenu(), userId);
    }

    /**
     * 查询系统菜单列表
     *
     * @param menu 菜单信息
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuList(SysMenu menu, Long userId)
    {
        List<SysMenu> menuList = null;
        // 管理员显示所有菜单信息
        if (userService.isAdmin(userId))
        {
            menuList = menuMapper.selectMenuList(menu);
        }
        else
        {
            menu.getParams().put("userId", userId);
            menuList = menuMapper.selectMenuListByUserId(menu);
        }
        menuList = repairedParentMenu(menuList);
        return menuList;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByUserId(Long userId)
    {
        List<String> perms = menuMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StringUtils.isNotEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据角色ID查询权限
     *
     * @param roleId 角色ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByRoleId(Long roleId)
    {
        List<String> perms = menuMapper.selectMenuPermsByRoleId(roleId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StringUtils.isNotEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据用户ID查询菜单
     *
     * @param userId 用户名称
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuTreeByUserId(Long userId)
    {
        List<SysMenu> menus = null;
        SysUser userVo = userService.selectUserById(userId);
        if(userVo==null)
            throw new ServiceException("用户不存在");
//        if (SecurityUtils.isAdmin(userVo.getUserType()))
//        {
//            //查询当前租户下所有菜单
//            menus = menuMapper.selectMenuTreeAll(userVo.getEnterpriseCode());
//        }
//        else
        {
            //查询当前租户下，当前用户有权限的菜单
//            if(SecurityConstants.IGNORE_APPLICATION_CODE.equals(SecurityUtils.getApplicationCode())) {
//                menus = menuMapper.selectMenuTreeByUser(userVo, null);
//            }else{
                menus = menuMapper.selectMenuTreeByUser(userVo, SecurityUtils.getApplicationCode());
                menus = repairedParentMenu(menus);
//            }
        }
        return getChildPerms(menus, 0);
    }

    /**
     * 补充缺失的上级菜单
     * @param menus
     * @return
     */
    private List<SysMenu> repairedParentMenu(List<SysMenu> menus) {
        List<SysMenu> temp = new ArrayList<>();
        temp.addAll(menus);
        SysMenu tempMenu = new SysMenu();
        for (SysMenu menu : temp) {
            if (menu.getParentId() == 0) {
                continue;
            }
            //补全上级菜单
            tempMenu.setMenuId(menu.getParentId());
            while (!menus.contains(tempMenu)) {
                menu = menuMapper.selectMenuById(menu.getParentId());
                if (menu == null) {
                    break;
                }
                menus.add(menu);
                if (menu.getParentId() == 0) {
                    break;
                }
                tempMenu.setMenuId(menu.getParentId());
            }
        }
        menus.sort(Comparator.comparing(SysMenu::getOrderNum));
        return menus;
    }

    /**
     * 根据角色ID查询菜单树信息
     *
     * @param roleId 角色ID
     * @return 选中菜单列表
     */
    @Override
    public List<Long> selectMenuListByRoleId(Long roleId)
    {
        SysRole role = roleMapper.selectRoleById(roleId);
        return menuMapper.selectMenuListByRoleId(roleId, role.isMenuCheckStrictly());
    }

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    @Override
    public List<RouterVo> buildMenus(List<SysMenu> menus)
    {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (SysMenu menu : menus)
        {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
            List<SysMenu> cMenus = menu.getChildren();
            if (StringUtils.isNotEmpty(cMenus) && UserConstants.TYPE_DIR.equals(menu.getMenuType()))
            {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            }
            else if (isMenuFrame(menu))
            {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            else if (menu.getParentId().intValue() == 0 && isInnerLink(menu))
            {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    @Override
    public List<SysMenu> buildMenuTree(List<SysMenu> menus)
    {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        List<Long> tempList = menus.stream().map(SysMenu::getMenuId).collect(Collectors.toList());
        for (Iterator<SysMenu> iterator = menus.iterator(); iterator.hasNext();)
        {
            SysMenu menu = (SysMenu) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId()))
            {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param menus 菜单列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<SysMenu> menus)
    {
        List<SysMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据菜单ID查询信息
     *
     * @param menuId 菜单ID
     * @return 菜单信息
     */
    @Override
    public SysMenu selectMenuById(Long menuId)
    {
        return menuMapper.selectMenuById(menuId);
    }

    /**
     * 是否存在菜单子节点
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public boolean hasChildByMenuId(Long menuId)
    {
        int result = menuMapper.hasChildByMenuId(menuId);
        return result > 0;
    }

    /**
     * 查询菜单使用数量
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public boolean checkMenuExistRole(Long menuId)
    {
        int result = roleMenuMapper.checkMenuExistRole(menuId);
        return result > 0;
    }

    /**
     * 新增保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int insertMenu(SysMenu menu)
    {
        return menuMapper.insertMenu(menu);
    }

    /**
     * 修改保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int updateMenu(SysMenu menu)
    {
        return menuMapper.updateMenu(menu);
    }

    /**
     * 删除菜单管理信息
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public int deleteMenuById(Long menuId)
    {
        return menuMapper.deleteMenuById(menuId);
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public boolean checkMenuNameUnique(SysMenu menu)
    {
        Long menuId = StringUtils.isNull(menu.getMenuId()) ? -1L : menu.getMenuId();
        SysMenu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId());
        if (StringUtils.isNotNull(info) && info.getMenuId().longValue() != menuId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int impMenu(ImpMenu menu) {
        //查询页面id
        ExtPage extPage = null;
        //检测页面id是否属于当前租户及应用
        extPage = verifyPageAccess(menu, extPage);
        //设置固定参数
        if(extPage!=null) {
            //组件页面
            menu.setComponent("business/page/pagerender");
            //页面id作为路径
            menu.setPath(String.valueOf(extPage.getId()));
            //设置路由参数
            menu.setQuery("{\"pageId\":\"" + extPage.getId() + "\"}");
        }
        //插入页面菜单
        int rownum = menuMapper.insertMenu(menu);

        if(extPage!=null) {
            //更新路由参数为：pageId:xxx,menuId:xxx
            menu.setQuery("{\"pageId\":\"" + extPage.getId() + "\",\"menuId\":\"" + menu.getMenuId() + "\"}");
            menuMapper.updateMenu(menu);
            //查询页面所有的按钮
            List<ExtButton> buttons;
            buttons = loadAllButton(extPage.getPageScheme());
            //循环插入按钮
            return insertButtonsForPage(menu, buttons);
        }else{
            return rownum;
        }
    }

    /**
     * 查询租户菜单列表
     *
     * @return
     */
    @Override
    public List<SysMenu> selectTenderMenuList(SysMenu menu) {
        List<SysMenu> menus =  menuMapper.selectTenderMenuList(menu);
        //补充父级菜单
        menus = repairedParentMenu(menus);
        return menus;
    }

    /**
     * 获取没有授权按钮列表
     *
     * @param userId
     * @param noPermissionButton
     * @return
     */
    @Override
    public List<String> getNoPermissionButtons(Long userId, NoPermissionButton noPermissionButton) {
        //1.获取菜单下的所有按钮(即子菜单）
        SysMenu searchMenu = new SysMenu();
        searchMenu.setParentId(noPermissionButton.getMenuId());
        List<SysMenu> childMenus = menuMapper.selectMenuList(searchMenu);
        ExtPage extPage =null;
        extPage = getPageById(noPermissionButton);
        List<ExtButton> buttons = loadAllButton(extPage.getPageScheme());
        //2.获取当前用户下这个菜单有权限的按钮
        List<SysMenu> authorizedButtons = menuMapper.selectPageButtonsByUserId(userId, childMenus);
        //第一个集合减去第二个集合
        // 将 childMenus 和 authorizedButtons 转换为 Set
        Set<String> childMenuIds = buttons.stream()
                .map(ExtButton::getId)
                .collect(Collectors.toSet());

        Set<String> authorizedButtonIds = authorizedButtons.stream()
                .map(SysMenu::getPerms)
                .collect(Collectors.toSet());

        // 求差集
        childMenuIds.removeAll(authorizedButtonIds);
        List<String> retList = new ArrayList<>(childMenuIds);
        return retList;
    }

    /**
     * 递归删除菜单
     *
     * @param menuId
     * @return
     */
    @Override
    public int recursionRemoveMenuById(Long menuId) {
        //根据menuId获取SysMenu
        SysMenu sysMenu = menuMapper.selectMenuById(menuId);
        List<SysMenu> sysMenus = new ArrayList<>();
        sysMenus.add(sysMenu);
        //递归获取所有子菜单
        List<SysMenu> childMenus = recursionGetAllChildList(sysMenus);
        sysMenus.addAll(childMenus);
        //递归检查菜单id是否被占用
        checkMenusExistRole(sysMenus);
        //递归删除菜单
        int rownum = deleteMenus(sysMenus);
        return rownum;
    }

    /**
     * 递归获取所有子菜单
     * @param sysMenus
     * @return
     */
    private List<SysMenu> recursionGetAllChildList(List<SysMenu> sysMenus) {
        List<SysMenu> childMenus = new ArrayList<>();
        SysMenu searchSysMenu = new SysMenu();
        for (SysMenu sysMenu : sysMenus) {
            searchSysMenu.setParentId(sysMenu.getMenuId());
            List<SysMenu> childMenu = menuMapper.selectMenuList(searchSysMenu);
            if(childMenu!=null && childMenu.size()>0){
                childMenus.addAll(childMenu);
                childMenus.addAll(recursionGetAllChildList(childMenu));
            }
        }
        return childMenus;
    }

    /**
     * 递归删除菜单
     * @param sysMenus
     * @return
     */
    private int deleteMenus(List<SysMenu> sysMenus) {
        int rownum = 0;
        for (SysMenu sysMenu : sysMenus) {
            rownum += menuMapper.deleteMenuById(sysMenu.getMenuId());
        }
        return rownum;
    }

    /**
     * 递归检查菜单id是否被占用
     * @param sysMenus
     */
    private void checkMenusExistRole(List<SysMenu> sysMenus) {
        for (SysMenu sysMenu : sysMenus) {
            if(checkMenuExistRole(sysMenu.getMenuId())){
                throw new ServiceException("菜单已被角色绑定，无法删除");
            }
        }
    }

    /**
     * 根据页面id获取页面内容
     * @param noPermissionButton
     * @return
     */
    private ExtPage getPageById(NoPermissionButton noPermissionButton) {
        ExtPage extPage = null;
        if(noPermissionButton.getPageId()!=0){

            AjaxResult ajaxResult = pageService.getPageById(noPermissionButton.getPageId(), noPermissionButton.getEnterpriseCode(), noPermissionButton.getApplicationCode());
            if(ajaxResult!=null && ajaxResult.isSuccess()){
                Object o = ajaxResult.get(AjaxResult.DATA_TAG);

                if(o !=null) {
                    String json = JSON.toJSONString(o);
                     extPage = JSON.parseObject(json, ExtPage.class);
                    if(!extPage.getEnterpriseCode().equals(noPermissionButton.getEnterpriseCode())  ||
                            !extPage.getApplicationCode().equals(noPermissionButton.getApplicationCode()))
                    {
                        throw new ServiceException("页面不属于当前租户及应用");
                    }
                }
            }
        }
        return extPage;
    }

    public List<SysMenu> filterChildMenusByIds(List<SysMenu> childMenus, Set<String> childMenuIds) {
        return childMenus.stream()
                .filter(menu -> childMenuIds.contains(menu.getPerms()))
                .collect(Collectors.toList());
    }
    /**
     * 在当前页面下插入按钮列表
     * @param menu
     * @param buttons
     * @return
     */
    private int insertButtonsForPage(ImpMenu menu, List<ExtButton> buttons) {
        SysMenu sysMenu = new SysMenu();
        int oderNumber = 1;
        sysMenu.setApplicationCode(menu.getApplicationCode());
        sysMenu.setEnterpriseCode(menu.getEnterpriseCode());
        sysMenu.setComponent("");
        sysMenu.setPath("#");
        sysMenu.setIsFrame("1");
        sysMenu.setIsCache("0");
        sysMenu.setVisible("0");
        sysMenu.setStatus("0");
        sysMenu.setIcon("#");
        sysMenu.setMenuType("F");
        sysMenu.setParentId(menu.getMenuId());
        sysMenu.setCreateBy(SecurityUtils.getUsername());
        for (ExtButton button : buttons) {
            sysMenu.setMenuName(button.getName());
            sysMenu.setOrderNum(oderNumber++);
            sysMenu.setPerms(button.getId());
            sysMenu.setCreateTime(DateUtils.getNowDate());
            menuMapper.insertMenu(sysMenu);
            sysMenu.setMenuId(null);
        }
        return oderNumber;
    }

    /**
     * 校验页面访问权限
     * @param menu
     * @param extPage
     * @return
     */
    private ExtPage verifyPageAccess(ImpMenu menu, ExtPage extPage) {
        if(menu.getPageCode()!=null){
            AjaxResult ajaxResult = pageService.getPageByCode(menu.getPageCode(),menu.getEnterpriseCode(),menu.getApplicationCode());
            if(ajaxResult!=null && ajaxResult.isSuccess()){
                Object o = ajaxResult.get(AjaxResult.DATA_TAG);

                if(o !=null) {
                    String json = JSON.toJSONString(o);
                    extPage = JSON.parseObject(json, ExtPage.class);
                    if(!extPage.getEnterpriseCode().equals(menu.getEnterpriseCode())  ||
                            !extPage.getApplicationCode().equals(menu.getApplicationCode()))
                    {
                        throw new ServiceException("页面不属于当前租户及应用");
                    }
                }
            }
        }
        return extPage;
    }

    /**
     * 提取页面所有按钮
     * @param pageScheme
     * @return
     */
    private List<ExtButton> loadAllButton(String pageScheme) {
        JSONObject schema = JSONObject.parseObject(pageScheme);
        List<TempNode> nodes = PageParseTreeBuilder.buildTree(schema, "button");
        List<ExtButton> buttons = PageParseTreeBuilder.getButtons(nodes);
        return buttons;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenu menu)
    {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu))
        {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu)
    {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu))
        {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame()))
        {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu))
        {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenu menu)
    {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu))
        {
            component = menu.getComponent();
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu))
        {
            component = UserConstants.INNER_LINK;
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu))
        {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenu menu)
    {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenu menu)
    {
        return menu.getIsFrame().equals(UserConstants.NO_FRAME) && StringUtils.ishttp(menu.getPath());
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenu menu)
    {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenu> getChildPerms(List<SysMenu> list, int parentId)
    {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext();)
        {
            SysMenu t = (SysMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId)
            {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t 子节点
     */
    private void recursionFn(List<SysMenu> list, SysMenu t)
    {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t)
    {
        List<SysMenu> tlist = new ArrayList<SysMenu>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext())
        {
            SysMenu n = (SysMenu) it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t)
    {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    public String innerLinkReplaceEach(String path)
    {
        return StringUtils.replaceEach(path, new String[] { Constants.HTTP, Constants.HTTPS, Constants.WWW, ".", ":" },
                new String[] { "", "", "", "/", "/" });
    }
}
